import { useState, useEffect } from 'react';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import Editor from '@monaco-editor/react';
import { X, Save, Play, Code, Eye } from 'lucide-react';

interface SubAgentConfig {
  id: string;
  name: string;
  description: string;
  prompt: string;
  tools?: string[];
  model?: 'sonnet' | 'opus' | 'haiku' | 'inherit';
  skillIds?: string[];
  category?: string;
  tags?: string[];
  isBuiltin?: boolean;
}

interface SubAgentEditorProps {
  agentId: string;
  onSave: (config: SubAgentConfig) => Promise<void>;
  onClose: () => void;
}

const AVAILABLE_TOOLS = [
  'Read', 'Write', 'Bash', 'Grep', 'Glob', 'List', 'Search'
];

const AVAILABLE_MODELS = [
  { value: 'sonnet', label: 'Claude Sonnet (Balanced)' },
  { value: 'opus', label: 'Claude Opus (Most Capable)' },
  { value: 'haiku', label: 'Claude Haiku (Fastest)' },
  { value: 'inherit', label: 'Inherit from Parent' },
];

export function SubAgentEditor({ agentId, onSave, onClose }: SubAgentEditorProps) {
  const [config, setConfig] = useState<SubAgentConfig | null>(null);
  const [mode, setMode] = useState<'visual' | 'code'>('visual');
  const [jsonCode, setJsonCode] = useState('');
  const [testing, setTesting] = useState(false);
  const [testResult, setTestResult] = useState<any>(null);
  const [testPrompt, setTestPrompt] = useState('');
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    loadAgent();
  }, [agentId]);

  const loadAgent = async () => {
    try {
      const response = await fetch(`http://localhost:3000/api/subagents/${agentId}`);
      const data = await response.json();
      if (data.success) {
        setConfig(data.data);
        setJsonCode(JSON.stringify(data.data, null, 2));
      } else {
        setError(data.error || 'Failed to load sub-agent');
      }
    } catch (err) {
      setError('Failed to load sub-agent: ' + err);
    }
  };

  const handleSave = async () => {
    if (!config) return;

    setSaving(true);
    setError(null);

    try {
      // If in code mode, parse JSON first
      let configToSave = config;
      if (mode === 'code') {
        try {
          configToSave = JSON.parse(jsonCode);
        } catch (err) {
          setError('Invalid JSON: ' + err);
          setSaving(false);
          return;
        }
      }

      await onSave(configToSave);
      onClose();
    } catch (err) {
      setError('Failed to save: ' + err);
    } finally {
      setSaving(false);
    }
  };

  const handleTest = async () => {
    if (!testPrompt.trim()) {
      setError('Please enter a test prompt');
      return;
    }

    setTesting(true);
    setTestResult(null);
    setError(null);

    try {
      // TODO: Implement actual test API call
      // For now, just simulate a test
      await new Promise(resolve => setTimeout(resolve, 1000));
      setTestResult({
        success: true,
        message: 'Test completed successfully',
        response: 'This is a simulated response from the sub-agent.',
      });
    } catch (err) {
      setError('Test failed: ' + err);
    } finally {
      setTesting(false);
    }
  };

  const handleCodeChange = (value: string | undefined) => {
    if (value !== undefined) {
      setJsonCode(value);
      try {
        const parsed = JSON.parse(value);
        setConfig(parsed);
        setError(null);
      } catch (err) {
        // Invalid JSON, don't update config
      }
    }
  };

  const handleVisualChange = (field: keyof SubAgentConfig, value: any) => {
    if (!config) return;
    const updated = { ...config, [field]: value };
    setConfig(updated);
    setJsonCode(JSON.stringify(updated, null, 2));
  };

  const toggleTool = (tool: string) => {
    if (!config) return;
    const tools = config.tools || [];
    const updated = tools.includes(tool)
      ? tools.filter(t => t !== tool)
      : [...tools, tool];
    handleVisualChange('tools', updated);
  };

  if (!config) {
    return (
      <div className="flex items-center justify-center h-full">
        <div className="text-center">
          <div className="text-lg font-medium">Loading...</div>
          {error && <div className="text-red-500 mt-2">{error}</div>}
        </div>
      </div>
    );
  }

  return (
    <div className="flex flex-col h-full">
      {/* Header */}
      <div className="border-b px-6 py-4 flex items-center justify-between">
        <div>
          <h2 className="text-xl font-semibold">Edit Sub-Agent</h2>
          <p className="text-sm text-muted-foreground mt-1">
            {config.name} {config.isBuiltin && <Badge variant="secondary" className="ml-2">Built-in</Badge>}
          </p>
        </div>
        <div className="flex items-center gap-2">
          <Button variant="outline" onClick={onClose}>
            <X className="w-4 h-4 mr-2" />
            Cancel
          </Button>
          <Button onClick={handleSave} disabled={saving || config.isBuiltin}>
            <Save className="w-4 h-4 mr-2" />
            {saving ? 'Saving...' : 'Save'}
          </Button>
        </div>
      </div>

      {/* Mode Tabs */}
      <div className="border-b px-6">
        <Tabs value={mode} onValueChange={(v) => setMode(v as 'visual' | 'code')}>
          <TabsList>
            <TabsTrigger value="visual">
              <Eye className="w-4 h-4 mr-2" />
              Visual Editor
            </TabsTrigger>
            <TabsTrigger value="code">
              <Code className="w-4 h-4 mr-2" />
              Code Editor
            </TabsTrigger>
          </TabsList>
        </Tabs>
      </div>

      {error && (
        <div className="mx-6 mt-4 p-3 bg-red-50 border border-red-200 rounded-md text-red-700 text-sm">
          {error}
        </div>
      )}

      {/* Content */}
      <div className="flex-1 overflow-hidden flex">
        {/* Editor Area */}
        <div className="flex-1 overflow-y-auto">
          {mode === 'visual' ? (
            <div className="p-6 space-y-6">
              {/* Basic Information */}
              <Card>
                <CardHeader>
                  <CardTitle>Basic Information</CardTitle>
                  <CardDescription>Configure the sub-agent's basic properties</CardDescription>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div>
                    <Label htmlFor="name">Name</Label>
                    <Input
                      id="name"
                      value={config.name}
                      onChange={(e) => handleVisualChange('name', e.target.value)}
                      disabled={config.isBuiltin}
                      placeholder="e.g., Code Reviewer"
                    />
                  </div>

                  <div>
                    <Label htmlFor="description">Description</Label>
                    <Textarea
                      id="description"
                      value={config.description}
                      onChange={(e) => handleVisualChange('description', e.target.value)}
                      disabled={config.isBuiltin}
                      placeholder="Describe when this sub-agent should be used..."
                      rows={3}
                    />
                    <p className="text-xs text-muted-foreground mt-1">
                      This helps Claude decide when to invoke this sub-agent
                    </p>
                  </div>

                  <div>
                    <Label htmlFor="prompt">System Prompt</Label>
                    <Textarea
                      id="prompt"
                      value={config.prompt}
                      onChange={(e) => handleVisualChange('prompt', e.target.value)}
                      disabled={config.isBuiltin}
                      placeholder="Define the sub-agent's role and behavior..."
                      rows={6}
                    />
                    <p className="text-xs text-muted-foreground mt-1">
                      {config.prompt.length} characters
                    </p>
                  </div>
                </CardContent>
              </Card>

              {/* Tools & Model */}
              <Card>
                <CardHeader>
                  <CardTitle>Tools & Model</CardTitle>
                  <CardDescription>Select available tools and model</CardDescription>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div>
                    <Label>Model</Label>
                    <div className="grid grid-cols-2 gap-2 mt-2">
                      {AVAILABLE_MODELS.map((model) => (
                        <Button
                          key={model.value}
                          variant={config.model === model.value ? 'default' : 'outline'}
                          onClick={() => handleVisualChange('model', model.value)}
                          disabled={config.isBuiltin}
                          className="justify-start"
                        >
                          {model.label}
                        </Button>
                      ))}
                    </div>
                  </div>

                  <div>
                    <Label>Tools</Label>
                    <div className="flex flex-wrap gap-2 mt-2">
                      {AVAILABLE_TOOLS.map((tool) => (
                        <Badge
                          key={tool}
                          variant={(config.tools || []).includes(tool) ? 'default' : 'outline'}
                          className="cursor-pointer"
                          onClick={() => !config.isBuiltin && toggleTool(tool)}
                        >
                          {tool}
                        </Badge>
                      ))}
                    </div>
                    <p className="text-xs text-muted-foreground mt-2">
                      {config.tools?.length || 0} tools selected. Leave empty to inherit all tools.
                    </p>
                  </div>
                </CardContent>
              </Card>
            </div>
          ) : (
            <div className="h-full">
              <Editor
                height="100%"
                language="json"
                value={jsonCode}
                onChange={handleCodeChange}
                theme="vs-dark"
                options={{
                  minimap: { enabled: false },
                  fontSize: 14,
                  lineNumbers: 'on',
                  formatOnPaste: true,
                  formatOnType: true,
                  readOnly: config.isBuiltin,
                }}
              />
            </div>
          )}
        </div>

        {/* Test Panel */}
        <div className="w-96 border-l flex flex-col">
          <div className="p-4 border-b">
            <h3 className="font-semibold">Test Sub-Agent</h3>
            <p className="text-sm text-muted-foreground mt-1">
              Test the sub-agent with a sample prompt
            </p>
          </div>

          <div className="flex-1 overflow-y-auto p-4 space-y-4">
            <div>
              <Label htmlFor="test-prompt">Test Prompt</Label>
              <Textarea
                id="test-prompt"
                value={testPrompt}
                onChange={(e) => setTestPrompt(e.target.value)}
                placeholder="Enter a test prompt..."
                rows={4}
              />
            </div>

            <Button onClick={handleTest} disabled={testing} className="w-full">
              <Play className="w-4 h-4 mr-2" />
              {testing ? 'Testing...' : 'Run Test'}
            </Button>

            {testResult && (
              <Card>
                <CardHeader>
                  <CardTitle className="text-sm">Test Result</CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="text-sm space-y-2">
                    <div className={testResult.success ? 'text-green-600' : 'text-red-600'}>
                      {testResult.message}
                    </div>
                    {testResult.response && (
                      <div className="mt-2 p-2 bg-muted rounded text-xs">
                        {testResult.response}
                      </div>
                    )}
                  </div>
                </CardContent>
              </Card>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

